package com.bw.interceptor;

import com.bw.common.JwtUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 通过request 获取到cookie
        Cookie[] cookies = request.getCookies();
        // 默认全拦截
        boolean flag = false;
        if (cookies != null){
            // 从众多cookie中 过滤出令牌
            for (Cookie cookie : cookies) {

                String name = cookie.getName();
                String value = cookie.getValue();

                if ("currentUserToken".equals(name)){
                    // 验证 令牌是否有效
                     flag = JwtUtils.validToken(value);
                }
            }
        }

        if (!flag){
            response.sendRedirect("/loginPage.do");
            return false;
        }

        return HandlerInterceptor.super.preHandle(request, response, handler);
    }
}
